package com.visikard.asynctask;

import java.util.ArrayList;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.visikard.application.UIMessage;
import com.visikard.item.ItemRedeemDetails;
import com.visikard.response.BaseResponse;
import com.visikard.response.GetDetailRedeemResponse;

public abstract class GetDetailsRedeemTask extends BaseTask {
	public static final int POS_MERCHANT_ID = 0;
	public static final int POS_REDEEM_TRANSACTION_ID = 1;
	public static final int POS_PURCHASE_TRANSACTION_ID = 2;

	public static final String KEY_REDEEM_COUNT = "redeemedCount";
	public static final String KEY_KARD_NUMBER = "kardNumber";
	public static final String KEY_ADDRESS = "address";
	public static final String KEY_STATUS = "status";
	public static final String KEY_PAYMENT_METHOD = "paymentMethod";
	public static final String KEY_REDEEM_CODE = "redeemptionCode";
	public static final String KEY_OTHER_REDEEM = "otherRedeem";

	public abstract GetDetailRedeemResponse executeService(long merchantId, long redeemTransactionId,
			long purchaseTransactionId);

	public GetDetailsRedeemTask(Handler handler) {
		super(handler);
	}

	public GetDetailsRedeemTask(Handler handler, boolean isShowProgress) {
		super(handler, isShowProgress);
	}

	@Override
	protected Object doBackgroundWork(Object... params) {

		// Get params
		long merchantId = (Long) params[POS_MERCHANT_ID];
		long redeemTransactionId = (Long) params[POS_REDEEM_TRANSACTION_ID];
		long purchaseTransactionId = (Long) params[POS_PURCHASE_TRANSACTION_ID];

		// Validation

		// Call service
		return executeService(merchantId, redeemTransactionId, purchaseTransactionId);
	}

	@Override
	protected boolean handleResult(Object result) {
		GetDetailRedeemResponse response = (GetDetailRedeemResponse) result;
		if (result != null) {
			switch (response.getErrorCode()) {
				case BaseResponse.SUCCESS:
					Message successMsg = new Message();
					successMsg.what = UIMessage.MSG_LOAD_DETAIL_HISTORY_SUCCESS;
					Bundle data = buildDataSuccessMessage(response);
					successMsg.setData(data);
					mUIHandler.sendMessage(successMsg);
					return true;
			}
		}
		return false;
	}

	private Bundle buildDataSuccessMessage(GetDetailRedeemResponse response) {
		Bundle data = new Bundle();

		data.putInt(KEY_REDEEM_COUNT, response.getRedeemCount());
		data.putString(KEY_KARD_NUMBER, response.getKardNumber());
		data.putString(KEY_ADDRESS, response.getAddress());
		data.putString(KEY_STATUS, response.getStatus());
		data.putParcelableArrayList(KEY_OTHER_REDEEM,
				(ArrayList<ItemRedeemDetails>) response.getListItemRedeemDetails());
		data.putString(KEY_PAYMENT_METHOD, response.getPaymentMethod());
		data.putString(KEY_REDEEM_CODE, response.getRedemptionCode());

		return data;
	}

}
